package com.jifeng.api.schedule;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jifeng.api.crud.entity.FeeConfigEntity;
import com.jifeng.api.crud.entity.OrderEntity;
import com.jifeng.api.crud.service.FeeConfigService;
import com.jifeng.api.crud.service.OrderService;
import com.jifeng.api.utils.SendSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ScheduleTask {

    @Autowired
    OrderService orderService;

    @Autowired
    FeeConfigService feeConfigService;

    @Autowired
    SendSmsUtils sendSmsUtils;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 每一分钟执行一次
     */
    @Scheduled(fixedRate = 60000)
    public void checkOrder() {
        try {
            FeeConfigEntity feeConfigEntity = feeConfigService.getById(1L);
            Integer baseHour = feeConfigEntity.getBaseHour();
            Integer maxHour = feeConfigEntity.getMaxHour();
            Integer extFee = feeConfigEntity.getExtFee();
            List<OrderEntity> orderEntities = orderService.list(new QueryWrapper<OrderEntity>().eq("state", 4));
            orderEntities.forEach(orderEntity -> {
                String mobile = orderEntity.getMobile();
                Date startFeeTime = orderEntity.getStartFeeTime();
                Date nowDate = new Date();
                long useHour = DateUtil.between(startFeeTime, nowDate, DateUnit.HOUR);
                if (useHour > baseHour && useHour < maxHour) {
                    if (redisTemplate.opsForValue().get(mobile+":2")==null){
                        // 超时收费
                        sendSmsUtils.sendSms(mobile,2,0,0  ,0,baseHour,extFee/100);
                        redisTemplate.opsForValue().set(mobile+":2","true",1, TimeUnit.DAYS);
                    }
                } else if (useHour > maxHour) {
                    if (redisTemplate.opsForValue().get(mobile+":0")==null){
                        // 超时归还
                        sendSmsUtils.sendSms(mobile,0,maxHour,0,0,0,0);
                        redisTemplate.opsForValue().set(mobile+":0","true",1, TimeUnit.DAYS);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("path：{}，errMsg：{}", "扫描现有未归还订单", e.getMessage());
        }
    }
}
